import React,{ useEffect, useState, useRef } from "react";
import dayjs from 'dayjs'
import { Button, Input, Table,Popconfirm,Pagination, Modal, Form,InputNumber,Select,DatePicker,message } from 'antd'
import './user.css'
import { getUser, addUser, editUser,delUser } from '../../api'
const { Search } = Input
const rules = [ { required: true } ]
const User = () => {
    const [ tableData, setTableData ] = useState([])
    const [ ajaxData, setAjaxData ] = useState({
        name: '',
        page:1,
        limit: 10,
    }) //参数
    const [currentId, setCurrentId] = useState('')
    const [isModalOpen,setIsModalOpen] = useState(false)
    const [total, setTotal] = useState(0)
    const [ tableHeight, setTableHeight ] = useState(450)
    const [pageType,setPageType] = useState(0)
    const [ winTitle, setWinTitle ] = useState('新增')
    const [ form ] = Form.useForm()
    const userRef = useRef()
    const handleClick = (type, rowData = {}) =>{
        setIsModalOpen(!isModalOpen)
        setPageType(type)
        if(type) {
            setCurrentId(rowData.id)
            // 编辑
            setWinTitle('编辑')
            const copyRowData = JSON.parse(JSON.stringify(rowData))
            copyRowData.birth = dayjs(copyRowData.birth)
            form.setFieldsValue(copyRowData)
        } else {
            // 新增
            setWinTitle('新增')
        }
    }
    const confirm = row => {
        delUser({ id: row.id })
            .then(_ => {
                message.success('删除成功')
                getTableData()
            })
    }
    const onSearch = val => {
        setAjaxData({ name: val, page:1, limit: 10 })
    }
    const handleTableChange = (page,pageSize) => {
        setAjaxData({ ...ajaxData, page, limit: pageSize})
    }
    const getTableData = () => {
        getUser(ajaxData).then(({ data }) => {
            setTableData(data.list)
            setTotal(data.count)
        })
    }
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            width: 80,
        },
        {
            title: '年龄',
            dataIndex: 'age',
            width: 80,
        },
        {
            title: '性别',
            dataIndex: 'sex',
            render: text => {
                return (
                    <span>{ text === 1 ? '男' : '女'}</span>
                )
            },
            width: 80,
        },
        {
            title: '出生日期',
            dataIndex: "birth",
            width: 200,
        },
        {
            title: '地址',
            dataIndex: 'addr'
        },
        {
            title: '操作',
            align: 'center',
            render: row => {
                return (
                    <div className="flex-box">
                        <Button autoInsertSpace style={{ marginRight: '5px' }} onClick={() => handleClick(1, row)}>编辑</Button>
                        <Popconfirm
                            title="确认删除"
                            description="确定要删除这条数据?"
                            onConfirm={ () => confirm(row)}
                            okText="确定"
                            cancelText="取消"
                        >
                        <Button type="primary" autoInsertSpace danger>删除</Button>
                        </Popconfirm>
                    </div>
                )
            },
            width: 150,
        }
    ]
    // 钩子函数，页面首次加载
    useEffect(() => {
        let tableHeight = userRef.current.offsetHeight - 32 - 55 - 32
        setTableHeight(tableHeight)
        getTableData()
    },[ajaxData])

    const handleCancel = () =>{
        setIsModalOpen(false)
        form.resetFields()
    }
    // 弹窗确定
    const handleOk = () => {
        form.validateFields()
            .then(val => {
                val.birth = dayjs(val.birth).format('YYYY-MM-DD')
                if(pageType) {
                  val.id = currentId
                  editUser(val).then(_ => {
                      handleCancel()
                      message.success('修改成功')
                      getTableData()
                  })
                } else {
                   addUser(val).then(_ => {
                       handleCancel()
                       message.success('新增成功')
                       getTableData()
                   })
                }
            }).catch(errorInfo => {
                console.error(errorInfo)
        })
    }
    return (
        <div className="user" ref={ userRef }>
            <div className="flex-box">
                <Button type={"primary"} onClick={() => handleClick(0)}>新增</Button>
                <Search onSearch={onSearch} rootClassName="search-input" placeholder="输入关键字查询" enterButton="查询" size="middle" />
            </div>
            <div className="table">
                <Table scroll={{ y:tableHeight }} pagination={false} tableLayout={"auto"}  rowKey={"id"} columns={columns} dataSource={tableData} />
                <Pagination onChange={handleTableChange}  defaultCurrent={ajaxData.page} total={total} />
            </div>
            <Modal title={`${winTitle}用户`} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Form
                    form={form}
                    labelCol={{
                        span: 6,
                    }}
                    wrapperCol={{
                        span: 18,
                    }}
                    layout="horizontal"
                    labelAlign="left"
                   >
                    <Form.Item name="name" rules={rules} label="姓名">
                        <Input />
                    </Form.Item>
                    <Form.Item name="age" rules={rules} label="年龄">
                        <InputNumber min={0} style={{ width:'100%' }} />
                    </Form.Item>
                    <Form.Item  name="sex" rules={rules} label="性别">
                        <Select>
                            <Select.Option value={0}>女</Select.Option>
                            <Select.Option value={1}>男</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="birth" rules={rules} label="出生日期">
                        <DatePicker format={"YYYY-MM-DD"}   style={{ width:'100%' }} />
                    </Form.Item>
                    <Form.Item name="addr" rules={rules} label="地址">
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
export default User
